package net.citrite.android;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class MeasureReport {
    private String file;
    private Severity severity;
    private Position position;
    private List<String> languages = new ArrayList<>();

    public void addLanguage(String lang) {
        languages.add(lang);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        MeasureReport o = (MeasureReport)obj;
        if (o.position.equals(this.position) && o.file.equals(this.file)) {
            return true;
        }
        return false;
    }

    public void setFile(String file) {
        this.file = file;
    }

    public void setPosition(Position position) {
        this.position = position;
    }

    public String getFile() {
        return file;
    }

    public Position getPosition() {
        return position;
    }

    @Override
    public String toString() {
        final int errCode = 5005;
        StringBuilder sb = new StringBuilder();
        File xmlFile = new File(file);
        Path related = Paths.get("").toAbsolutePath().relativize(xmlFile.toPath());
        sb.append(related.toString());
        sb.append(",");
        // line
        sb.append(position.getStartPos());
        sb.append(",");
        // column
        sb.append(0);
        sb.append(",");
        // columnEnd
        try {
            StringBuilder tmp = new StringBuilder();
            List<String> lines = java.nio.file.Files.readAllLines(xmlFile.toPath(), Charset.forName("UTF-8"));

            for (int pos = position.getStartPos(); pos < position.getEndPos(); pos++) {
                tmp.append(lines.get(pos));
            }
            sb.append(tmp.length());
        } catch (IOException e) {
            sb.append(0);
            e.printStackTrace();
        } finally {
            sb.append(",");
        }
        // severity
        sb.append(severity);
        sb.append(",");
        // code
        sb.append(errCode);
        sb.append(",");
        // context
        StringBuilder tmp = new StringBuilder();
        tmp.append(String.format("%s: ", position.getLabel()));
        for (int i = 0; i < languages.size(); i++) {
            if (i > 0) {
                tmp.append(", ");
            }
            tmp.append(languages.get(i));
        }
        sb.append(String.format("\"%s\"", tmp.toString()));
        return sb.toString();
    }

    public Severity getSeverity() {
        return severity;
    }

    public void setSeverity(Severity severity) {
        this.severity = severity;
    }
}
